<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>面试结果总览 - AI智能面试系统</title>
    <link href="/vendors/bootstrap/bootstrap.min.css" rel="stylesheet">
    <link href="/vendors/fontawesome/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #667eea;
            --secondary-color: #764ba2;
            --success-color: #28a745;
            --warning-color: #ffc107;
            --danger-color: #dc3545;
            --info-color: #17a2b8;
            --text-dark: #2d3748;
            --text-light: #718096;
            --bg-light: #f7fafc;
        }

        /* 统一导航栏样式 */
        .unified-navbar {
            background: white !important;
            border-bottom: 1px solid #e5e7eb !important;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1) !important;
            position: fixed !important;
            top: 0 !important;
            left: 0 !important;
            z-index: 1000 !important;
            height: 70px !important;
            width: 100% !important;
            margin: 0 !important;
            padding: 0 !important;
        }

        .unified-navbar-container {
            width: 100%;
            padding: 0 24px;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .unified-navbar-left {
            flex-shrink: 0;
        }

        .unified-navbar-brand {
            display: flex;
            align-items: center;
            text-decoration: none;
            color: #1f2937;
            font-weight: 700;
            font-size: 1.5rem;
        }

        .unified-navbar-brand i {
            color: var(--primary-color);
            margin-right: 8px;
            font-size: 1.2rem;
        }

        .unified-navbar-brand:hover {
            color: var(--primary-color);
            text-decoration: none;
        }

        .unified-navbar-center {
            flex: 1;
            display: flex;
            justify-content: center;
        }

        .unified-navbar-menu {
            display: flex;
            align-items: center;
            gap: 40px;
        }

        .unified-navbar-right {
            flex-shrink: 0;
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .unified-nav-item {
            display: flex;
            align-items: center;
            text-decoration: none;
            color: #6b7280;
            font-weight: 500;
            font-size: 14px;
            padding: 8px 12px;
            border-radius: 6px;
            transition: all 0.2s ease;
        }

        .unified-nav-item i {
            margin-right: 6px;
            font-size: 14px;
        }

        .unified-nav-item:hover {
            color: var(--primary-color);
            background: #eff6ff;
            text-decoration: none;
        }

        .unified-nav-item.active {
            color: var(--primary-color);
            background: #eff6ff;
            font-weight: 600;
        }

        .unified-nav-item.user-info {
            background: #f3f4f6;
            color: var(--primary-color);
            font-weight: 600;
            cursor: default;
        }

        .unified-nav-item.user-info:hover {
            background: #f3f4f6;
            color: var(--primary-color);
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            margin: 0;
            padding: 80px 20px 20px 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            padding: 30px;
            color: white;
            text-align: center;
            position: relative;
        }
        
        .header h1 {
            font-size: 28px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        
        .back-button {
            position: absolute;
            left: 30px;
            top: 50%;
            transform: translateY(-50%);
            background: rgba(255,255,255,0.1);
            color: white;
            border: 2px solid rgba(255,255,255,0.3);
            border-radius: 25px;
            padding: 8px 16px;
            text-decoration: none;
            transition: all 0.3s ease;
        }
        
        .back-button:hover {
            background: rgba(255,255,255,0.2);
            color: white;
            text-decoration: none;
        }
        
        .content {
            padding: 30px;
        }
        
        .score-overview {
            text-align: center;
            margin-bottom: 40px;
        }
        
        .main-score {
            font-size: 64px;
            font-weight: bold;
            color: #4facfe;
            margin: 20px 0;
        }
        
        .score-bar {
            width: 100%;
            height: 12px;
            background: #e0e0e0;
            border-radius: 6px;
            margin: 20px 0;
            overflow: hidden;
        }
        
        .score-progress {
            height: 100%;
            background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
            border-radius: 6px;
            transition: width 1s ease;
        }
        
        .position-info {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 20px;
            margin: 20px 0;
            font-size: 16px;
            color: #555;
        }
        
        .analysis-section {
            background: #f8f9fa;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 25px;
        }
        
        .section-title {
            display: flex;
            align-items: center;
            font-size: 18px;
            font-weight: bold;
            color: #333;
            margin-bottom: 20px;
        }
        
        .section-title i {
            margin-right: 10px;
            color: #4facfe;
        }
        
        .answer-analysis {
            margin-bottom: 20px;
        }
        
        .question-header {
            background: white;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 10px;
            border-left: 4px solid #4facfe;
        }
        
        .question-title {
            font-weight: bold;
            color: #333;
            margin-bottom: 5px;
        }
        
        .question-score {
            color: #28a745;
            font-weight: bold;
        }
        
        .analysis-details {
            background: white;
            padding: 15px;
            border-radius: 10px;
            margin-left: 20px;
        }
        
        .highlights {
            margin-bottom: 15px;
        }
        
        .highlight-item, .improvement-item {
            display: flex;
            align-items: flex-start;
            margin-bottom: 8px;
            padding: 8px;
            border-radius: 6px;
        }
        
        .highlight-item {
            background: #d4edda;
            color: #155724;
        }
        
        .improvement-item {
            background: #f8d7da;
            color: #721c24;
        }
        
        .highlight-item i, .improvement-item i {
            margin-right: 8px;
            margin-top: 2px;
        }
        
        .improvements-section {
            background: #fff3cd;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 25px;
        }
        
        .improvement-category {
            margin-bottom: 20px;
        }
        
        .category-title {
            display: flex;
            align-items: center;
            font-weight: bold;
            color: #856404;
            margin-bottom: 10px;
        }
        
        .category-title i {
            margin-right: 8px;
        }
        
        /* 未回答题目的样式 */
        .answer-analysis.unanswered {
            border-left: 4px solid #dc3545;
            background: linear-gradient(135deg, #fff5f5 0%, #fff 100%);
        }
        
        .question-score.unanswered-status {
            color: #dc3545;
            font-weight: bold;
        }
        
        .unanswered-notice {
            padding: 15px;
            background: #fff5f5;
            border-radius: 8px;
            border: 1px solid #f5c6cb;
        }
        
        .unanswered-item {
            display: flex;
            align-items: flex-start;
            margin-bottom: 8px;
            color: #721c24;
        }
        
        .unanswered-item:last-child {
            margin-bottom: 0;
        }
        
        .unanswered-item i {
            color: #dc3545;
            margin-right: 8px;
            margin-top: 2px;
            font-size: 14px;
        }
        
        .final-result {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 25px;
            text-align: center;
        }
        
        .result-rating {
            font-size: 36px;
            font-weight: bold;
            margin: 15px 0;
        }
        
        .result-recommendation {
            font-size: 18px;
            margin: 10px 0;
        }
        
        .result-validity {
            font-size: 14px;
            opacity: 0.8;
            margin-top: 15px;
        }
        
        .action-buttons {
            display: flex;
            justify-content: center;
            gap: 15px;
            margin-top: 20px;
        }
        
        .btn-action {
            background: rgba(255,255,255,0.2);
            color: white;
            border: 2px solid rgba(255,255,255,0.3);
            border-radius: 25px;
            padding: 10px 20px;
            text-decoration: none;
            transition: all 0.3s ease;
        }
        
        .btn-action:hover {
            background: rgba(255,255,255,0.3);
            color: white;
            text-decoration: none;
        }
        
        .loading {
            text-align: center;
            padding: 60px 20px;
            color: #888;
        }
        
        .error {
            text-align: center;
            padding: 60px 20px;
            color: #dc3545;
        }
        
        @media (max-width: 768px) {
            .unified-navbar-container {
                padding: 0 16px;
            }
            
            .unified-navbar-menu {
                gap: 15px;
            }
            
            .unified-nav-item {
                font-size: 13px;
                padding: 6px 8px;
            }
            
            .unified-navbar-brand {
                font-size: 1.3rem;
            }
            
            .position-info {
                flex-direction: column;
                gap: 10px;
            }
            
            .main-score {
                font-size: 48px;
            }
            
            .action-buttons {
                flex-direction: column;
                align-items: center;
            }
        }
        
        @media (max-width: 576px) {
            .unified-navbar-center {
                display: none;
            }
            
            .unified-navbar-right {
                gap: 10px;
            }
        }
    </style>
</head>
<body>
    <!-- 统一导航栏 -->
    <header class="unified-navbar">
        <div class="unified-navbar-container">
            <div class="unified-navbar-left">
                <a href="/" class="unified-navbar-brand">
                    <i class="fas fa-briefcase"></i>
                    <span>AI超级面试官平台</span>
                </a>
            </div>
            
            <div class="unified-navbar-center">
                <nav class="unified-navbar-menu">
                    <a href="/" class="unified-nav-item">首页</a>
                    <a href="/chat" class="unified-nav-item">
                        <i class="fas fa-robot"></i>
                        AI智能助手
                    </a>
                    <a href="/interview" class="unified-nav-item active">
                        <i class="fas fa-clipboard-question"></i>
                        模拟面试题
                    </a>
                    <a href="/job-search" class="unified-nav-item">
                        <i class="fas fa-search"></i>
                        职位搜索
                    </a>
                </nav>
            </div>
            
            <div class="unified-navbar-right" id="navbar-right">
                <a href="/login" class="unified-nav-item">
                    <i class="fas fa-sign-in-alt"></i>
                    登录
                </a>
                <a href="/register" class="unified-nav-item">
                    <i class="fas fa-user-plus"></i>
                    注册
                </a>
            </div>
        </div>
    </header>

    <div class="container">
        <div class="header">
            <a href="/interview/records" class="back-button">
                <i class="fas fa-arrow-left"></i> 返回记录
            </a>
            <h1><i class="fas fa-chart-bar"></i> 面试结果总览</h1>
            <p>详细的面试表现分析和改进建议</p>
        </div>
        
        <div class="content">
            <div class="loading" id="loadingState">
                正在加载分析结果...
            </div>
            
            <div class="error" id="errorState" style="display: none;">
                <i class="fas fa-exclamation-triangle" style="font-size: 48px; margin-bottom: 20px;"></i>
                <p id="errorMessage">加载失败，请稍后重试</p>
            </div>
            
            <div id="analysisContent" style="display: none;">
                <!-- 总分概览 -->
                <div class="score-overview">
                    <div class="main-score" id="totalScore">82</div>
                    <div class="score-bar">
                        <div class="score-progress" id="scoreProgress" style="width: 82%"></div>
                    </div>
                    <div class="position-info">
                        <span><strong>岗位匹配度:</strong> <span id="positionMatch">前端开发工程师 (85%)</span></span>
                    </div>
                </div>
                
                <!-- 回答内容分析 -->
                <div class="analysis-section">
                    <div class="section-title">
                        <i class="fas fa-comments"></i>
                        回答内容分析
                    </div>
                    <div id="answerAnalysisList">
                        <!-- 答案分析内容将通过JavaScript动态生成 -->
                    </div>
                </div>
                
                <!-- 改进建议 -->
                <div class="improvements-section">
                    <div class="section-title">
                        <i class="fas fa-lightbulb"></i>
                        改进建议
                    </div>
                    <div id="improvementsList">
                        <!-- 改进建议将通过JavaScript动态生成 -->
                    </div>
                </div>
                
                <!-- 最终评估结果 -->
                <div class="final-result">
                    <div class="section-title" style="color: white; justify-content: center;">
                        <i class="fas fa-trophy"></i>
                        最终评估结果
                    </div>
                    <div class="result-rating" id="finalRating">B+</div>
                    <div class="result-recommendation" id="recommendation">综合评分：B+ （建议进入复试）</div>
                    <div class="result-validity">结果有效期：30天</div>
                    
                    <div class="action-buttons">
                        <a href="#" class="btn-action" onclick="generateReport(event)">
                            生成详细报告
                        </a>
                        <a href="#" class="btn-action" onclick="scheduleInterview()">
                            预约模拟面试
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="/vendors/jquery/jquery.min.js"></script>
    <script src="/js/auth.js"></script>
    <script>
        let sessionId = null;
        
                 document.addEventListener('DOMContentLoaded', function() {
             // 检查认证状态并更新导航栏
             checkAuthAndUpdateNavbar();
             
             // 从URL参数获取sessionId
             const urlParams = new URLSearchParams(window.location.search);
             sessionId = urlParams.get('sessionId');
             
             if (!sessionId) {
                 showError('缺少会话参数');
                 return;
             }
             
             loadAnalysisResult();
         });
         
         function checkAuthAndUpdateNavbar() {
             const token = localStorage.getItem('token');
             const username = localStorage.getItem('username');
             const navbarRight = document.getElementById('navbar-right');
             
             if (token && username) {
                 navbarRight.innerHTML = `
                     <span class="unified-nav-item user-info">
                         <i class="fas fa-user"></i>
                         ${username}
                     </span>
                     <a href="#" class="unified-nav-item" onclick="logout()">
                         <i class="fas fa-sign-out-alt"></i>
                         退出
                     </a>
                 `;
             }
         }
         
         function logout() {
             localStorage.removeItem('token');
             localStorage.removeItem('username');
             window.location.href = '/login';
         }
        
        async function loadAnalysisResult() {
            try {
                // 首先尝试从URL参数获取token，如果没有则从localStorage获取
                const urlParams = new URLSearchParams(window.location.search);
                let token = urlParams.get('token');
                
                if (!token) {
                    token = localStorage.getItem('token');
                }
                
                if (!token) {
                    window.location.href = '/login';
                    return;
                }
                
                // 如果从URL参数获取到token，保存到localStorage以便后续使用
                if (urlParams.get('token')) {
                    localStorage.setItem('token', token);
                }
                
                const response = await fetch(`/interview/analysis/${sessionId}`, {
                    method: 'GET',
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                });
                
                const data = await response.json();
                console.log('分析结果数据:', data);
                
                if (data.success) {
                    displayAnalysisResult(data.data);
                } else {
                    if (response.status === 401) {
                        localStorage.removeItem('token');
                        window.location.href = '/login';
                    } else {
                        showError(data.message);
                    }
                }
                
            } catch (error) {
                console.error('加载分析结果失败:', error);
                showError('网络错误，请稍后重试');
            } finally {
                document.getElementById('loadingState').style.display = 'none';
            }
        }
        
        function displayAnalysisResult(data) {
            const session = data.session;
            const analysis = data.analysis;
            const answers = data.answers;
            
            // 显示总分和岗位匹配度
            const totalScore = session.totalScore || 82;
            const positionMatchRate = session.positionMatchRate || 85;
            const comprehensiveRating = session.comprehensiveRating || 'B+';
            
            document.getElementById('totalScore').textContent = totalScore;
            document.getElementById('scoreProgress').style.width = totalScore + '%';
            document.getElementById('positionMatch').textContent = `${session.targetPosition} (${positionMatchRate}%)`;
            document.getElementById('finalRating').textContent = comprehensiveRating;
            
            // 生成推荐文本
            let recommendation = '';
            if (totalScore >= 90) {
                recommendation = '综合评分：A+ （强烈推荐录用）';
            } else if (totalScore >= 85) {
                recommendation = '综合评分：A/B+ （建议进入复试）';
            } else if (totalScore >= 75) {
                recommendation = '综合评分：B/C+ （需要进一步考察）';
            } else {
                recommendation = '综合评分：C （建议加强训练后重新面试）';
            }
            document.getElementById('recommendation').textContent = recommendation;
            
            // 显示答案分析
            if (answers && answers.length > 0) {
                displayAnswerAnalysis(answers);
            }
            
            // 显示改进建议
            if (analysis) {
                displayImprovements(analysis);
            }
            
            // 显示内容
            document.getElementById('analysisContent').style.display = 'block';
        }
        
        function displayAnswerAnalysis(answers) {
            const container = document.getElementById('answerAnalysisList');
            let html = '';
            
            answers.forEach((answer, index) => {
                // 检查是否有答案内容
                const hasAnswer = answer.answerContent && answer.answerContent.trim() !== '';
                
                if (hasAnswer) {
                    // 有回答的题目
                    const score = answer.aiScore || Math.floor(Math.random() * 20) + 80; // 随机分数作为示例
                    const status = answer.aiAnalysis || '完整';
                    
                    // 解析优点和改进建议
                    let highlights = [];
                    let improvements = [];
                    
                    try {
                        if (answer.strengthPoints) {
                            highlights = JSON.parse(answer.strengthPoints);
                        }
                        if (answer.improvementPoints) {
                            improvements = JSON.parse(answer.improvementPoints);
                        }
                    } catch (e) {
                        // 如果解析失败，使用默认值
                        highlights = ['回答内容完整', '逻辑思路清晰'];
                        improvements = ['可以增加更多具体示例', '表达可以更加生动'];
                    }
                    
                    html += `
                        <div class="answer-analysis">
                            <div class="question-header">
                                <div class="question-title">Q${index + 1}: ${answer.questionTitle}</div>
                                <div class="question-score">回答完整度: ${status} - 得分: ${score}分</div>
                            </div>
                            <div class="analysis-details">
                                <div class="highlights">
                                    ${highlights.map(item => `
                                        <div class="highlight-item">
                                            <i class="fas fa-check"></i>
                                            <span>${item}</span>
                                        </div>
                                    `).join('')}
                                </div>
                                <div class="improvements">
                                    ${improvements.map(item => `
                                        <div class="improvement-item">
                                            <i class="fas fa-exclamation"></i>
                                            <span>${item}</span>
                                        </div>
                                    `).join('')}
                                </div>
                            </div>
                        </div>
                    `;
                } else {
                    // 未回答的题目
                    html += `
                        <div class="answer-analysis unanswered">
                            <div class="question-header">
                                <div class="question-title">Q${index + 1}: ${answer.questionTitle}</div>
                                <div class="question-score unanswered-status">未回答 - 得分: 0分</div>
                            </div>
                            <div class="analysis-details">
                                <div class="unanswered-notice">
                                    <div class="unanswered-item">
                                        <i class="fas fa-exclamation-triangle"></i>
                                        <span>此题目未回答，建议补充完整回答内容</span>
                                    </div>
                                    <div class="unanswered-item">
                                        <i class="fas fa-lightbulb"></i>
                                        <span>建议针对此题目准备详细的回答思路和实例</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;
                }
            });
            
            container.innerHTML = html;
        }
        
        function displayImprovements(analysis) {
            const container = document.getElementById('improvementsList');
            
            // 解析改进建议
            let improvements = {};
            try {
                if (analysis.improvements) {
                    improvements = JSON.parse(analysis.improvements);
                }
            } catch (e) {
                // 使用默认改进建议
                improvements = {
                    '技术表达': ['建议补充更多技术细节', '增加代码示例说明'],
                    '表达能力': ['使用STAR法则结构化回答', '控制语速，保持逻辑清晰']
                };
            }
            
            let html = '';
            Object.keys(improvements).forEach(category => {
                html += `
                    <div class="improvement-category">
                        <div class="category-title">
                            <i class="fas fa-arrow-up"></i>
                            ${category}
                        </div>
                        ${improvements[category].map(item => `
                            <div class="improvement-item">
                                <i class="fas fa-arrow-right"></i>
                                <span>${item}</span>
                            </div>
                        `).join('')}
                    </div>
                `;
            });
            
            container.innerHTML = html;
        }
        
        function showError(message) {
            document.getElementById('errorMessage').textContent = message;
            document.getElementById('errorState').style.display = 'block';
        }
        
        async function generateReport(event) {
            try {
                // 显示加载状态
                const button = event ? event.target : document.querySelector('.btn-action');
                const originalText = button.textContent;
                button.textContent = '生成中...';
                button.disabled = true;
                
                // 获取token
                const token = localStorage.getItem('token');
                if (!token) {
                    alert('请先登录');
                    return;
                }
                
                // 调用PDF生成API
                const response = await fetch(`/interview/analysis/${sessionId}/pdf`, {
                    method: 'GET',
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                });
                
                if (response.ok) {
                    // 在新标签页中打开报告
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    
                    // 在新窗口中打开报告
                    const newWindow = window.open(url, '_blank');
                    if (newWindow) {
                        newWindow.document.title = `面试分析报告 - ${sessionId}`;
                        // 显示成功消息
                        alert('详细报告已生成！您可以在新标签页中查看或打印。');
                    } else {
                        // 如果弹窗被阻止，提供下载链接
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = `interview_report_${sessionId}_${new Date().getTime()}.html`;
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                        alert('详细报告已生成并开始下载！');
                    }
                    
                    // 延迟释放URL
                    setTimeout(() => window.URL.revokeObjectURL(url), 1000);
                } else if (response.status === 401) {
                    alert('请先登录');
                    window.location.href = '/login';
                } else {
                    alert('生成报告失败，请稍后重试');
                }
                
            } catch (error) {
                console.error('生成报告失败:', error);
                alert('生成报告失败，请检查网络连接');
            } finally {
                // 恢复按钮状态
                button.textContent = originalText;
                button.disabled = false;
            }
        }
        
        function scheduleInterview() {
            alert('模拟面试预约功能开发中...');
        }
    </script>
</body>
</html>